package com.example.app12_data_storage.utils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;

/**
 * Sqlite数据库操作工具类
 * @author lijiguo
 */
public class DbHelper extends SQLiteOpenHelper {

    private static final String TAG = "DbHelper";

    public DbHelper(@Nullable Context context, int version) {
        super(context, "data.db", null, version);
    }

    /**
     * 数据库文件不存在并且获取数据库连接时才会创建
     * 当数据库文件创建时调用1次
     * 可以创建表和初始化数据
     * @param db The database.
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.i(TAG, "onCreate: 数据库初始化~~");
        // 建表
        String sql = "create table person(_id integer primary key autoincrement, " +
                "name varchar, age int)";
        db.execSQL(sql);
        // 初始化数据
        db.execSQL("insert into person(name, age) values ('Tom', 18)");
    }

    /**
     * 数据库版本号更新时调用
     * @param db The database.
     * @param oldVersion The old database version.
     * @param newVersion The new database version.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i(TAG, "onUpgrade: 数据库更新~~");
    }
}
